#include <iostream>
#include <string>
#include <ctime>
#include <cassert>
#include <unistd.h>
#include "Socket.hpp"
#include "Protocol.hpp"

static void Usage(const std::string &proc)
{
    std::cout << "\nUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

//  ./clientcal ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(0);
    }

    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    Sock sockfd;
    sockfd.Socket();
    bool r = sockfd.Connect(serverip, serverport);
    if (!r)
        return 1;

    // 发送计算请求给服务端
    Request req(1, 2, '+');
    std::string package;
    req.Serialize(&package);
    req.DebugPrint();
    package = Encode(package);
    write(sockfd.Fd(), package.c_str(), sizeof(package));

    char buffer[128];
    std::string inbuffer_stream;
    ssize_t n = read(sockfd.Fd(), buffer, sizeof(buffer));
    if (n > 0)
    {
        buffer[n] = 0;
        inbuffer_stream += buffer; // "len"\n"result code"\n
        std::cout << inbuffer_stream << std::endl;
        std::string content;
        bool r = Decode(inbuffer_stream, &content); // "result code
        assert(r);
        Response resp;
        r = resp.Deserialize(content);
        assert(r);
        resp.DebugPrint();
    }
    sockfd.Close();
    return 0;
}